<!-- 临床病史 家族史 FamilyHistory -->
<template>
  <div class="page-center">
    <div class="medical-form">
      <el-form :model="formData" label-width="140px" class="info-form" label-position="left">
        <el-divider content-position="left">
          <h3>个人史</h3>
        </el-divider>

        <el-row :gutter="12">
          <!-- 家族史 -->
          <el-col :span="24">
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>家族史信息</span>
              </div>
              <el-form-item label="家族史">
                <div class="display-value info-value personal-history-content">
                  {{ display(formData.familyHistory) }}
                </div>
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { personalFamily } from '@/api/dataEntry/ClinicalHistory'

export default {
  name: 'FamilyHistory',
  data() {
    return {
      formData: {
        id: 0,
        children: 0,
        sexLife: {
          frequency: '',
          contraception: '',
          difficulty: ''
        },
        familyHistory: ''
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters('patient', ['robustPatientId', 'patientFallbackData'])
  },
  watch: {
    robustPatientId: {
      handler(newId) {
        if (newId) {
          this.loadData(newId)
        } else {
          this.resetForm()
        }
      },
      immediate: true
    }
  },
  async mounted() {
    // 如果当前没有患者信息，尝试从存储恢复
    if (!this.robustPatientId) {
      const restored = await this.restorePatientFromStorage()
      if (restored) {
        this.loadData(restored.id || restored.patientId)
      }
    }
  },
  methods: {
    ...mapActions('patient', ['restorePatientFromStorage']),

    async loadData(patientId) {
      if (this.loading) return

      this.loading = true
      try {
        const res = await personalFamily({ recordId: patientId })
        this.handleResponseData(res)
      } catch (error) {
        console.error('加载个人史失败:', error)
        this.applyFallbackData()
      } finally {
        this.loading = false
      }
    },

    handleResponseData(res) {
      const payload = res?.data?.data ?? res?.data ?? res ?? {}

      if (payload && Object.keys(payload).length > 0) {
        // 确保 sexLife 对象结构完整
        const processedData = {
          ...payload,
          sexLife: {
            frequency: payload.sexLife?.frequency || '',
            contraception: payload.sexLife?.contraception || '',
            difficulty: payload.sexLife?.difficulty || ''
          }
        }

        this.formData = {
          ...this.formData,
          ...processedData
        }
      }
    },

    applyFallbackData() {
      const patient = this.patientFallbackData
      if (patient) {
        // 从患者数据中提取可能的个人史信息
        const personalHistoryData = {
          children: patient.children,
          familyHistory: patient.familyHistory
        }

        // 处理性生活史数据
        if (patient.sexLife) {
          personalHistoryData.sexLife = {
            frequency: patient.sexLife.frequency || '',
            contraception: patient.sexLife.contraception || '',
            difficulty: patient.sexLife.difficulty || ''
          }
        }

        // 过滤掉空值，避免覆盖现有数据
        Object.keys(personalHistoryData).forEach(key => {
          if (personalHistoryData[key] !== undefined && personalHistoryData[key] !== null && personalHistoryData[key] !== '') {
            if (key === 'sexLife') {
              // 合并 sexLife 对象
              this.formData.sexLife = {
                ...this.formData.sexLife,
                ...personalHistoryData.sexLife
              }
            } else {
              this.formData[key] = personalHistoryData[key]
            }
          }
        })
      }
    },

    resetForm() {
      this.formData = {
        id: 0,
        children: 0,
        sexLife: {
          frequency: '',
          contraception: '',
          difficulty: ''
        },
        familyHistory: ''
      }
    },

    display(val) {
      if (val === null || val === undefined || String(val).trim() === '') return '-'
      return val
    }
  }
}
</script>

<!-- 引入共享样式 -->
<style src="@/styles/shared.css"></style>

<style scoped>
.personal-history-content {
  white-space: pre-wrap;
  line-height: 1.6;
  min-height: 80px;
  padding: 8px 0;
}
</style>
